import bpy
import re
from uuid import uuid4
from bpy.types import Operator
from ...addon.naming import FluidLabNaming
from bpy.props import StringProperty
from ...libs.functions.get_common_vars import get_common_vars
from ...libs.functions.collections import create_new_collection
from ...libs.functions.object import name_with_zfill
from .base_class_forces_add import FLUIDLAB_OT_fluid_forces_add_base_class

class FLUIDLAB_OT_fluid_forces_groups_list_add(FLUIDLAB_OT_fluid_forces_add_base_class):
    bl_idname = "fluidlab.fluid_forces_groups_list_add"
    bl_label = "Add New Force Group"
    bl_description = "Add Force Group to List"
    bl_options = {"REGISTER", "UNDO"}

    group_name: StringProperty(default="")

    def execute(self, context):
        
        if not self.group_name:
            self.report({'ERROR'}, "Invalid Name!")
            return {'CANCELLED'}

        fluid_forces_groups = get_common_vars(context, get_fluid_forces_groups=True)

        self.create_forces_main_coll_if_not_exit(context)

        # Group collection:
        new_coll = bpy.data.collections.get(self.group_name)
        if new_coll:
            self.report({'ERROR'}, f"Collection {self.group_name} already exist!")
            return {'CANCELLED'}
        
        new_coll = create_new_collection(context, self.group_name, False)
        new_coll[FluidLabNaming.FORCES_GROUP_COLL] = True
        
        id_name = str(uuid4())[:6]
        collection_place = bpy.data.collections
        label_txt = name_with_zfill(context, new_coll.name, collection_place)
        fluid_forces_groups.add_item(id_name, label_txt, new_coll)

        return {'FINISHED'}

    def invoke(self, context, event):
        
        # Sugiero el nombre:
        collection_place = bpy.data.collections
        desired_name = FluidLabNaming.FORCES_GROUP_COLL
        new_coll_name = name_with_zfill(context, desired_name, collection_place)
        self.group_name = new_coll_name

        return context.window_manager.invoke_props_dialog(self, width=200)

    def draw(self, context):
        
        layout = self.layout
        layout.use_property_decorate = False
        layout.use_property_split = False
        
        group_name = layout.column(align=True)
        if len(self.group_name) <= 0:
            group_name.alert = True
        group_name.prop(self, "group_name", text="Name")
